const { query } = require('../config/db');
const { validateOrderAccess } = require('../utils/roleAuth');
const pricingEngine = require('../utils/pricingEngine');

/**
 * 获取今日订单统计数据
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getTodayOrdersStats(req, res) {
  try {
    const parkingLotId = req.parkingOperator.parking_lot_id;
    const today = new Date().toISOString().split('T')[0]; // 获取今天的日期 YYYY-MM-DD

    // 查询今日订单统计
    const statsQuery = `
      SELECT 
        COUNT(CASE WHEN status = 'pending_payment' THEN 1 END) as pending_payment,
        COUNT(CASE WHEN status = 'in_progress' AND planned_start_time >= ? THEN 1 END) as expected_entry,
        COUNT(CASE WHEN status = 'in_progress' AND planned_end_time <= ? THEN 1 END) as expected_exit,
        COUNT(*) as total_orders
      FROM orders 
      WHERE parking_lot_id = ? 
        AND DATE(created_at) = ?
    `;

    const todayEnd = `${today} 23:59:59`;
    const result = await query(statsQuery, [today, todayEnd, parkingLotId, today]);
    
    const stats = result[0] || {
      pending_payment: 0,
      expected_entry: 0,
      expected_exit: 0,
      total_orders: 0
    };

    res.status(200).json({
      success: true,
      data: {
        pending_payment: stats.pending_payment,
        expected_entry: stats.expected_entry,
        expected_exit: stats.expected_exit,
        total_orders: stats.total_orders
      }
    });

  } catch (error) {
    console.error('获取今日订单统计错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 获取今日业绩统计数据
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getTodayRevenueStats(req, res) {
  try {
    const parkingLotId = req.parkingOperator.parking_lot_id;
    const today = new Date().toISOString().split('T')[0]; // 获取今天的日期 YYYY-MM-DD

    // 查询今日业绩统计
    const revenueQuery = `
      SELECT 
        COALESCE(SUM(CASE WHEN status = 'completed' THEN final_amount END), 0) as actual_payment,
        COALESCE(SUM(CASE WHEN status IN ('in_progress', 'pending_payment') THEN final_amount END), 0) as expected_payment,
        COALESCE(SUM(CASE WHEN status = 'completed' AND paid_at IS NOT NULL THEN final_amount END), 0) as completed_payment
      FROM orders 
      WHERE parking_lot_id = ? 
        AND DATE(created_at) = ?
    `;

    const result = await query(revenueQuery, [parkingLotId, today]);
    
    const revenue = result[0] || {
      actual_payment: 0,
      expected_payment: 0,
      completed_payment: 0
    };

    res.status(200).json({
      success: true,
      data: {
        actual_payment: parseFloat(revenue.actual_payment).toFixed(2),
        expected_payment: parseFloat(revenue.expected_payment).toFixed(2),
        completed_payment: parseFloat(revenue.completed_payment).toFixed(2)
      }
    });

  } catch (error) {
    console.error('获取今日业绩统计错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 获取今日车位统计数据
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getTodayParkingStats(req, res) {
  try {
    const parkingLotId = req.parkingOperator.parking_lot_id;
    const totalSpaces = req.parkingOperator.total_spaces || 0;

    // 查询当前占用的车位数（进行中的订单）
    const occupiedQuery = `
      SELECT COUNT(*) as occupied_spaces
      FROM orders 
      WHERE parking_lot_id = ? 
        AND status = 'in_progress'
        AND actual_start_time IS NOT NULL
        AND (actual_end_time IS NULL OR actual_end_time > NOW())
    `;

    const result = await query(occupiedQuery, [parkingLotId]);
    const occupiedSpaces = result[0]?.occupied_spaces || 0;
    const availableSpaces = Math.max(0, totalSpaces - occupiedSpaces);

    res.status(200).json({
      success: true,
      data: {
        total_spaces: totalSpaces,
        occupied_spaces: occupiedSpaces,
        available_spaces: availableSpaces
      }
    });

  } catch (error) {
    console.error('获取今日车位统计错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 获取停车场订单列表
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getParkingOperatorOrders(req, res) {
  try {
    const parkingLotId = req.parkingOperator.parking_lot_id;
    const { page = 1, limit = 20, status } = req.query;

    const pageNum = parseInt(page) || 1;
    const limitNum = parseInt(limit) || 20;
    const offset = (pageNum - 1) * limitNum;

    let whereClause = 'WHERE o.parking_lot_id = ?';
    let queryParams = [parkingLotId];

    // 状态筛选
    if (status && status !== 'all') {
      whereClause += ' AND o.status = ?';
      queryParams.push(status);
    }

    // 查询总数
    const countQuery = `
      SELECT COUNT(*) as total
      FROM orders o
      ${whereClause}
    `;

    const countResult = await query(countQuery, queryParams);
    const total = countResult[0].total;

    // 查询订单列表
    const ordersQuery = `
      SELECT 
        o.id,
        o.order_number,
        o.license_plate,
        o.planned_start_time,
        o.planned_end_time,
        o.actual_start_time,
        o.actual_end_time,
        o.total_amount,
        o.discount_amount,
        o.final_amount,
        o.status,
        o.payment_method,
        o.paid_at,
        o.created_at,
        o.updated_at,
        u.nickname as user_nickname
      FROM orders o
      LEFT JOIN users u ON o.user_id = u.id
      ${whereClause}
      ORDER BY o.created_at DESC
      LIMIT ${limitNum} OFFSET ${offset}
    `;

    const orders = await query(ordersQuery, queryParams);

    // 格式化订单数据
    const formattedOrders = orders.map(order => ({
      ...order,
      total_amount: parseFloat(order.total_amount),
      discount_amount: parseFloat(order.discount_amount),
      final_amount: parseFloat(order.final_amount)
    }));

    res.status(200).json({
      success: true,
      data: {
        list: formattedOrders,
        total,
        page: pageNum,
        limit: limitNum,
        totalPages: Math.ceil(total / limitNum)
      }
    });

  } catch (error) {
    console.error('获取停车场订单列表错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 获取单个订单详情
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getOrderDetail(req, res) {
  try {
    const { orderId } = req.params;
    const parkingLotId = req.parkingOperator.parking_lot_id;

    if (!orderId || isNaN(orderId)) {
      return res.status(400).json({
        success: false,
        message: '订单ID无效'
      });
    }

    // 查询订单详情
    const orderQuery = `
      SELECT
        o.id,
        o.order_number,
        o.license_plate,
        o.parking_type,
        o.planned_start_time,
        o.planned_end_time,
        o.actual_start_time,
        o.actual_end_time,
        o.total_amount,
        o.discount_amount,
        o.final_amount,
        o.status,
        o.payment_method,
        o.paid_at,
        o.created_at,
        o.updated_at,
        u.nickname as user_nickname,
        u.phone_number as user_phone,
        pl.name as parking_lot_name,
        pl.address as parking_lot_address
      FROM orders o
      LEFT JOIN users u ON o.user_id = u.id
      LEFT JOIN parking_lots pl ON o.parking_lot_id = pl.id
      WHERE o.id = ? AND o.parking_lot_id = ?
    `;

    const result = await query(orderQuery, [orderId, parkingLotId]);

    if (result.length === 0) {
      return res.status(404).json({
        success: false,
        message: '订单不存在或无权限访问'
      });
    }

    const order = result[0];

    // 格式化订单数据
    const formattedOrder = {
      ...order,
      total_amount: parseFloat(order.total_amount),
      discount_amount: parseFloat(order.discount_amount),
      final_amount: parseFloat(order.final_amount)
    };

    res.status(200).json({
      success: true,
      data: formattedOrder
    });

  } catch (error) {
    console.error('获取订单详情错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 格式化日期时间为MySQL格式
 * @param {string} dateTimeString - ISO日期时间字符串
 * @returns {string} MySQL格式的日期时间字符串
 */
function formatDateTimeForMySQL(dateTimeString) {
  if (!dateTimeString) return null;
  
  const date = new Date(dateTimeString);
  if (isNaN(date.getTime())) return null;
  
  // 转换为 YYYY-MM-DD HH:MM:SS 格式
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

/**
 * 更新订单实际入场和出场时间
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function updateOrderActualTime(req, res) {
  try {
    const { orderId } = req.params;
    const { actual_start_time, actual_end_time, notes } = req.body;
    const userId = req.user.id;

    if (!orderId || isNaN(orderId)) {
      return res.status(400).json({
        success: false,
        message: '订单ID无效'
      });
    }

    // 验证用户是否有权限操作此订单
    const hasAccess = await validateOrderAccess(userId, orderId);
    if (!hasAccess) {
      return res.status(403).json({
        success: false,
        message: '无权限操作此订单'
      });
    }

    // 格式化时间为MySQL格式
    let formattedStartTime = null;
    let formattedEndTime = null;

    if (actual_start_time) {
      formattedStartTime = formatDateTimeForMySQL(actual_start_time);
      if (!formattedStartTime) {
        return res.status(400).json({ success: false, message: '实际入场时间格式不正确' });
      }
    }

    if (actual_end_time) {
      formattedEndTime = formatDateTimeForMySQL(actual_end_time);
      if (!formattedEndTime) {
        return res.status(400).json({ success: false, message: '实际出场时间格式不正确' });
      }
    }

    // 验证时间逻辑（若两者均提供）
    if (actual_start_time && actual_end_time) {
      const startTime = new Date(actual_start_time);
      const endTime = new Date(actual_end_time);
      if (endTime <= startTime) {
        return res.status(400).json({ success: false, message: '实际出场时间必须晚于实际入场时间' });
      }
    }

    // 获取订单信息用于重新计算费用
    const orderInfoQuery = `
      SELECT 
        id, parking_lot_id, parking_type, planned_start_time, planned_end_time,
        actual_start_time, actual_end_time, total_amount, discount_amount, final_amount, status
      FROM orders 
      WHERE id = ?
    `;
    const orderInfoResult = await query(orderInfoQuery, [orderId]);
    if (orderInfoResult.length === 0) {
      return res.status(404).json({ success: false, message: '订单不存在' });
    }
    const orderInfo = orderInfoResult[0];

    // 构建更新SQL
    let updateFields = [];
    let updateParams = [];

    // 需要更新的实际时间字段
    if (formattedStartTime) {
      updateFields.push('actual_start_time = ?');
      updateParams.push(formattedStartTime);
    }
    if (formattedEndTime) {
      updateFields.push('actual_end_time = ?');
      updateParams.push(formattedEndTime);
    }

    // 计算用于计价的区间（缺失一侧则回退到已有的实际/计划时间）
    const calcStart = formattedStartTime || orderInfo.actual_start_time || orderInfo.planned_start_time;
    const calcEnd = formattedEndTime || orderInfo.actual_end_time || orderInfo.planned_end_time;

    let newTotalAmount = null;
    let pricingOk = false;

    try {
      // 任一实际时间有变化即尝试重算
      if (formattedStartTime || formattedEndTime) {
        const priceResult = await pricingEngine.calculatePrice(
          orderInfo.parking_lot_id,
          calcStart,
          calcEnd,
          orderInfo.parking_type
        );
        if (priceResult.success) {
          newTotalAmount = priceResult.total_amount;
          pricingOk = true;
          // 仅更新应付总额，不动 final_amount（已付金额）
          updateFields.push('total_amount = ?');
          updateParams.push(newTotalAmount);
          console.log(`订单费用重新计算 - 订单ID: ${orderId}, 原费用: ${orderInfo.total_amount}, 新费用: ${newTotalAmount}`);
        } else {
          console.warn(`订单费用重新计算失败 - 订单ID: ${orderId}, 错误: ${priceResult.error}`);
        }
      }
    } catch (priceError) {
      console.error(`订单费用重新计算异常 - 订单ID: ${orderId}:`, priceError);
      // 价格计算失败不阻断时间更新
    }

    // 若设置了实际离场时间，按差额决定状态；并同步计划离场时间
    if (formattedEndTime && pricingOk && newTotalAmount != null) {
      const paidAmount = parseFloat(orderInfo.final_amount) || 0;
      const discountAmount = parseFloat(orderInfo.discount_amount) || 0;
      // 计算应付金额：新总费用 - 优惠券折扣（优惠券永久有效）
      const shouldPayAmount = Math.max(0, newTotalAmount - discountAmount);
      const diff = Math.round((shouldPayAmount - paidAmount) * 100) / 100;
      // 同步计划离场时间为实际离场
      updateFields.push('planned_end_time = ?');
      updateParams.push(formattedEndTime);
      if (diff > 0.005) {
        updateFields.push('status = ?');
        updateParams.push('pending_additional_payment');
      } else {
        updateFields.push('status = ?');
        updateParams.push('completed');
      }
    }

    if (notes) {
      // 暂保留，未来可写入操作日志表
    }

    if (updateFields.length === 0) {
      return res.status(400).json({ success: false, message: '没有需要更新的字段' });
    }

    updateFields.push('updated_at = NOW()');
    updateParams.push(orderId);

    const updateQuery = `
      UPDATE orders 
      SET ${updateFields.join(', ')}
      WHERE id = ?
    `;
    const result = await query(updateQuery, updateParams);

    if (result.affectedRows === 0) {
      return res.status(404).json({ success: false, message: '订单不存在' });
    }

    console.log(`订单时间更新 - 订单ID: ${orderId}, 操作员: ${userId}, 备注: ${notes || '无'}`);

    // 获取更新后的订单信息
    const updatedOrderQuery = `
      SELECT 
        id, order_number, license_plate, 
        planned_start_time, planned_end_time,
        actual_start_time, actual_end_time,
        status, updated_at
      FROM orders 
      WHERE id = ?
    `;
    const updatedOrder = await query(updatedOrderQuery, [orderId]);

    res.status(200).json({
      success: true,
      message: '订单时间更新成功',
      data: updatedOrder[0]
    });

  } catch (error) {
    console.error('更新订单实际时间错误:', error);
    res.status(500).json({ success: false, message: '服务器内部错误' });
  }
}

/**
 * 获取停车场基本信息（运营商端）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getParkingLotInfo(req, res) {
  try {
    const parkingLotId = req.parkingOperator.parking_lot_id;

    const parkingLotQuery = `
      SELECT 
        p.*,
        c.name as category_name
      FROM parking_lots p
      LEFT JOIN parking_lot_categories c ON p.category_id = c.id
      WHERE p.id = ?
    `;

    const result = await query(parkingLotQuery, [parkingLotId]);

    if (result.length === 0) {
      return res.status(404).json({
        success: false,
        message: '停车场不存在'
      });
    }

    const parkingLot = result[0];

    console.log('=== 停车场数据处理开始 ===');
    console.log('原始数据:', {
      image_urls: parkingLot.image_urls,
      service_facilities: parkingLot.service_facilities,
      price_rules: parkingLot.price_rules,
      business_documents: parkingLot.business_documents
    });

    // 格式化图片URL
    if (parkingLot.image_urls) {
      if (typeof parkingLot.image_urls === 'string') {
        try {
          parkingLot.image_urls = JSON.parse(parkingLot.image_urls);
        } catch (error) {
          console.error('image_urls JSON解析失败:', error);
          parkingLot.image_urls = [];
        }
      } else if (!Array.isArray(parkingLot.image_urls)) {
        parkingLot.image_urls = [];
      }
    } else {
      parkingLot.image_urls = [];
    }

    // 格式化服务设施
    if (parkingLot.service_facilities) {
      if (typeof parkingLot.service_facilities === 'string') {
        try {
          parkingLot.service_facilities = JSON.parse(parkingLot.service_facilities);
        } catch (error) {
          console.error('service_facilities JSON解析失败:', error);
          parkingLot.service_facilities = [];
        }
      } else if (!Array.isArray(parkingLot.service_facilities)) {
        parkingLot.service_facilities = [];
      }
    } else {
      parkingLot.service_facilities = [];
    }

    // 格式化价格规则
    if (parkingLot.price_rules) {
      if (typeof parkingLot.price_rules === 'string') {
        try {
          parkingLot.price_rules = JSON.parse(parkingLot.price_rules);
        } catch (error) {
          console.error('price_rules JSON解析失败:', error);
          parkingLot.price_rules = null;
        }
      }
    }

    // 格式化营业资料
    if (parkingLot.business_documents) {
      if (typeof parkingLot.business_documents === 'string') {
        try {
          parkingLot.business_documents = JSON.parse(parkingLot.business_documents);
        } catch (error) {
          console.error('business_documents JSON解析失败:', error);
          parkingLot.business_documents = {};
        }
      } else if (typeof parkingLot.business_documents !== 'object') {
        parkingLot.business_documents = {};
      }
    } else {
      parkingLot.business_documents = {};
    }

    console.log('处理后数据:', {
      image_urls: parkingLot.image_urls,
      service_facilities: parkingLot.service_facilities,
      price_rules: parkingLot.price_rules,
      business_documents: parkingLot.business_documents
    });
    console.log('=== 停车场数据处理结束 ===');

    res.status(200).json({
      success: true,
      data: parkingLot
    });

  } catch (error) {
    console.error('获取停车场信息错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 获取停车场关闭日期列表
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getClosedDates(req, res) {
  try {
    const parkingLotId = req.parkingOperator.parking_lot_id;

    const closedDatesQuery = `
      SELECT closed_date, reason, created_at
      FROM parking_lot_closed_dates 
      WHERE parking_lot_id = ?
      ORDER BY closed_date ASC
    `;

    const closedDates = await query(closedDatesQuery, [parkingLotId]);

    res.status(200).json({
      success: true,
      data: closedDates
    });

  } catch (error) {
    console.error('获取关闭日期错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 获取停车场评价列表（停车场管理人员）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getParkingLotReviews(req, res) {
  try {
    const parkingLotId = req.parkingOperator.parking_lot_id;
    const { page = 1, pageSize = 10, status = '' } = req.query;

    console.log(`📝 停车场管理人员获取评价列表 - 停车场ID: ${parkingLotId}, 页码: ${page}, 状态: ${status}`);

    // 参数验证
    const pageNum = parseInt(page);
    const pageSizeNum = parseInt(pageSize);

    if (pageNum < 1 || pageSizeNum < 1 || pageSizeNum > 100) {
      return res.status(400).json({
        success: false,
        message: '分页参数无效'
      });
    }

    // 构建查询条件
    let whereConditions = ['r.parking_lot_id = ?'];
    let queryParams = [parkingLotId];

    if (status.trim()) {
      whereConditions.push('r.status = ?');
      queryParams.push(status.trim());
    }

    const whereClause = `WHERE ${whereConditions.join(' AND ')}`;

    // 查询总数
    const countQuery = `
      SELECT COUNT(*) as total
      FROM reviews r
      ${whereClause}
    `;

    const countResult = await query(countQuery, queryParams);
    const total = countResult[0].total;

    // 查询列表数据
    const offset = (pageNum - 1) * pageSizeNum;
    const listQuery = `
      SELECT
        r.id,
        r.order_id,
        r.user_id,
        r.parking_lot_id,
        r.rating,
        r.comment,
        r.status,
        r.created_at,
        u.nickname as user_nickname,
        u.avatar_url as user_avatar,
        p.name as parking_lot_name,
        o.order_number
      FROM reviews r
      LEFT JOIN users u ON r.user_id = u.id
      LEFT JOIN parking_lots p ON r.parking_lot_id = p.id
      LEFT JOIN orders o ON r.order_id = o.id
      ${whereClause}
      ORDER BY r.created_at DESC
      LIMIT ${pageSizeNum} OFFSET ${offset}
    `;

    const listResult = await query(listQuery, queryParams);

    // 获取每个评价的回复
    for (let review of listResult) {
      const repliesQuery = `
        SELECT
          rr.id,
          rr.content,
          rr.created_at,
          u.nickname as reply_user_nickname
        FROM review_replies rr
        LEFT JOIN users u ON rr.user_id = u.id
        WHERE rr.review_id = ?
        ORDER BY rr.created_at ASC
      `;
      
      const replies = await query(repliesQuery, [review.id]);
      review.replies = replies;
    }

    res.status(200).json({
      success: true,
      data: {
        list: listResult,
        total,
        page: pageNum,
        pageSize: pageSizeNum,
        totalPages: Math.ceil(total / pageSizeNum)
      }
    });

  } catch (error) {
    console.error('停车场管理人员获取评价列表错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 更新评价状态（停车场管理人员）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function updateReviewStatus(req, res) {
  try {
    const parkingLotId = req.parkingOperator.parking_lot_id;
    const { id } = req.params;
    const { status } = req.body;

    console.log(`🔄 停车场管理人员更新评价状态 - 停车场ID: ${parkingLotId}, 评价ID: ${id}, 状态: ${status}`);

    if (!id || isNaN(id)) {
      return res.status(400).json({
        success: false,
        message: '评价ID无效'
      });
    }

    if (!['visible', 'hidden'].includes(status)) {
      return res.status(400).json({
        success: false,
        message: '状态值无效'
      });
    }

    // 检查评价是否存在且属于当前停车场
    const existingReview = await query(
      'SELECT id FROM reviews WHERE id = ? AND parking_lot_id = ?', 
      [id, parkingLotId]
    );
    
    if (existingReview.length === 0) {
      return res.status(404).json({
        success: false,
        message: '评价不存在或无权限操作'
      });
    }

    // 更新状态
    await query('UPDATE reviews SET status = ? WHERE id = ?', [status, id]);

    res.status(200).json({
      success: true,
      message: '评价状态更新成功'
    });

  } catch (error) {
    console.error('停车场管理人员更新评价状态错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 回复评价（停车场管理人员）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function replyToReview(req, res) {
  try {
    const parkingLotId = req.parkingOperator.parking_lot_id;
    const userId = req.user.id; // 使用req.user.id而不是req.parkingOperator.user_id
    const { id } = req.params;
    const { content } = req.body;

    console.log(`💬 停车场管理人员回复评价 - 停车场ID: ${parkingLotId}, 评价ID: ${id}, 用户ID: ${userId}`);

    if (!id || isNaN(id)) {
      return res.status(400).json({
        success: false,
        message: '评价ID无效'
      });
    }

    if (!content || content.trim().length === 0) {
      return res.status(400).json({
        success: false,
        message: '回复内容不能为空'
      });
    }

    if (content.trim().length > 500) {
      return res.status(400).json({
        success: false,
        message: '回复内容不能超过500字符'
      });
    }

    // 检查评价是否存在且属于当前停车场
    const existingReview = await query(
      'SELECT id FROM reviews WHERE id = ? AND parking_lot_id = ?', 
      [id, parkingLotId]
    );
    
    if (existingReview.length === 0) {
      return res.status(404).json({
        success: false,
        message: '评价不存在或无权限操作'
      });
    }

    // 插入回复
    const insertQuery = `
      INSERT INTO review_replies (review_id, user_id, content)
      VALUES (?, ?, ?)
    `;

    const result = await query(insertQuery, [id, userId, content.trim()]);

    res.status(201).json({
      success: true,
      message: '回复成功',
      data: {
        id: result.insertId
      }
    });

  } catch (error) {
    console.error('停车场管理人员回复评价错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

module.exports = {
  getTodayOrdersStats,
  getTodayRevenueStats,
  getTodayParkingStats,
  getParkingOperatorOrders,
  getOrderDetail,
  updateOrderActualTime,
  getParkingLotInfo,
  getClosedDates,
  getParkingLotReviews,
  updateReviewStatus,
  replyToReview
};